
//add_header_element ( "script", { "type":"text/javascript", "src":"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" } );

MediaUpload = function( vars )	{

	Object.extend( obj = $$( '.MediaUpload' ).pop(), MediaUpload.proto );
	obj.vars		= vars;
	
	return obj.prepare();
}



MediaUpload.proto =	{

	prepare		: function() {

		tm = setTimeout( $j, 200, this.init.bind( this ));
		return this;
	},
	
	init		: function() {
	
		up.$jdrop 	= $j('#drop-area');
		up.vars		= this.vars;	
		
		up.$jdrop.bind('dragenter',up.enter);
		up.$jdrop.bind('dragleave',up.leave);
		up.$jdrop.bind('dragover',up.over);
		up.$jdrop.bind('drop',up.drop);
		
		//$j('#status').click(up.cancel);
		
		up.xhr = new XMLHttpRequest();
		up.xhr.upload.addEventListener('progress', up.uploadProgress , false);
		up.xhr.upload.addEventListener('load', up.uploadLoaded , false);
		
	},
	
	end			: function( xhr ) {
		
		this.vars.succes( xhr );
	}
}
var up = {
	
	$jdrop :		null,
	queue :			[],
	processing :	null,
	uploading :		false,
	binaryReader :	null,
	dataReader :	null,
	xhr:			null,
	vars:			null,
	counter:		0,
	
	enter : function(e){
		$j(e.target).addClass('hover');
		return false;
	},
	
	leave : function(e){
		$j(e.target).removeClass('hover');
		return false;
	},
	
	over : function(e){
		return false;
	},
	
	drop : function(e){
		$j(e.target).removeClass('hover');
		
		up.$jdrop.html( ' ' );
		var files = e.originalEvent.dataTransfer.files;
		for (var i = 0; i<files.length; i++) {
			var file = files[i];
			up.queue.push(file);
		}
		
		if(up.uploading == false) {
			up.uploading = true;
			up.process();
		}
		
		return false;
	},
	
	process : function() {
	
		up.processing = up.queue.shift();
		
		//up.$jdrop.append('<div>'+up.processing.name+'</div>');
		
		if(window.FileReader) { //firefox 3.6, Chrome 6, Webkit

			if(up.processing.type.match(/image/gi) != null) { //is an image - read it
				up.dataReader = new FileReader();
				if(up.dataReader.addEventListener) { //firefox
					up.dataReader.addEventListener('loadend', up.binaryLoad, false);
					up.dataReader.addEventListener('error', up.loadError, false);
					up.dataReader.addEventListener('progress', up.loadProgress, false);
				} else { //chrome / webkit
					up.dataReader.onloadend = up.binaryLoad;
					up.dataReader.onerror = up.loadError;
					up.dataReader.onprogress = up.loadProgress;
				}
				up.dataReader.readAsDataURL(up.processing);
			}
			
			up.binaryReader = new FileReader();
			if(up.binaryReader.addEventListener) { //firefox
				up.binaryReader.addEventListener('loadend', up.binaryLoad, false);
				up.binaryReader.addEventListener('error', up.loadError, false);
				up.binaryReader.addEventListener('progress', up.loadProgress, false);
			} else { //chrome / webkit
				up.binaryReader.onloadend = up.binaryLoad;
				up.binaryReader.onerror = up.loadError;
				up.binaryReader.onprogress = up.loadProgress;
			}
			up.binaryReader.readAsBinaryString(up.processing);
			
			
		} else { // safari 5 + others?
		
			up.xhr.abort(); //make sure xhr is a new request
			up.xhr.open('POST', '/html5_upload.php?up=true', true);
		
			up.xhr.setRequestHeader('UP-FILENAME', up.processing.name);
			up.xhr.setRequestHeader('UP-SIZE', up.processing.size);
			up.xhr.setRequestHeader('UP-TYPE', up.processing.type);
			
			up.xhr.send(up.processing); 
			up.xhr.onload = up.onload;
		}
		
	},
	
	loadError : function(e) {
		switch(e.target.error.code) {
			case e.target.error.NOT_FOUND_ERR:
				alert('File Not Found!');
			break;
			case e.target.error.NOT_READABLE_ERR:
				alert('File is not readable');
			break;
			case e.target.error.ABORT_ERR:
			break; 
			default:
				alert('An error occurred reading this file.');
		};

	},
	
	loadProgress : function(e) {
		if (e.lengthComputable) {
			var percentage = Math.round((e.loaded * 100) / e.total);
			$j('#status').html('loaded: '+percentage+'%');
		}
	},
		
	binaryLoad : function(e) {
		
		up.$jdrop[0].vars = up.vars;
		
		var isimage = (up.processing.type.match(/image/gi)!=null);

		Object.extend( up.$jdrop[0].vars, { name: up.processing.name, fileSize: up.processing.fileSize, fileType: up.processing.type, auth: init.userid, up: true });
		getstring = Object.toQueryString( up.$jdrop[0].vars );
	
		if(isimage && up.dataReader.readyState == 2 && up.binaryReader.readyState == 2 || !isimage && up.binaryReader.readyState == 2 ) {
			
			up.xhr.abort(); //make sure xhr is a new request
			
			var binary = e.target.result;
			
			if(up.xhr.sendAsBinary != null) { //firefox
			
				up.xhr.open( 'POST', '/upload.mod?base64=true&' + getstring, true );
				//up.xhr.open('POST', engine.path.local + 'control.upload.php?' + getstring, true);
	
				var boundary = 'xxxxxxxxx';
			    
				var body = '--' + boundary + "\r\n";  
				body += "Content-Disposition: form-data; name='upload'; filename='" + up.processing.name + "'\r\n";  
				body += "Content-Type: application/octet-stream\r\n\r\n";  
				body += binary + "\r\n";  
				body += '--' + boundary + '--';  
			    
			    up.xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);
			    up.xhr.sendAsBinary(body);        	
			    
		    } else { //for browsers that don't support sendAsBinary yet
			 
			 	
				up.xhr.open( 'POST', '/upload.mod?base64=true&' + getstring, true );
				//up.xhr.open('POST', engine.path.local + 'control.upload.php?' + getstring, true);
			 	//up.xhr.open('POST', engine.path.local + 'control.upload.php?base64=true&' + getstring, true);
			 
			 	up.xhr.setRequestHeader('UP-FILENAME', up.processing.name);
			 	up.xhr.setRequestHeader('UP-SIZE', up.processing.size);
			 	up.xhr.setRequestHeader('UP-TYPE', up.processing.type);
			 	
				up.xhr.send(window.btoa(binary)); 
				
		    }
			 
			up.xhr.onload = up.onload;
		}
	},
	
	uploadProgress : function(e) {
		if (e.lengthComputable) {
			var percentage = Math.round((e.loaded * 100) / e.total);
			$j('#status').html('uploaded: '+percentage+'%');
		}
	},
	
	uploadLoaded : function(e) {
		$j('#status').html('Uploaded: 100%');
	},
	
	onload : function (e) {
		
		var response = $j.parseJSON(up.xhr.responseText );
		if( response.success == 1 ) {
	
			up.counter = up.counter + 1
			$j('#drop-area').append( '<div class="file">' + response.file + ' uploaded!</div>' );			

		}
		
		if(up.queue.length > 0) {
			up.process();
		} else {
			up.uploading = false;
			$j('#status').html('Queue Uploaded');
			if( $j('#drop-area .msg').length > 0 ) {
				//$j('#drop-area .msg').text( up.counter + ' ' + response.msg.toLowerCase());
				//console.log( 'foo' );
			} else {
				$j('#drop-area').append( '<div class="msg">' + up.counter + ' ' + response.msg.toLowerCase() + '</div>' );			
			}
			//up.$jdrop[0].end( up.xhr )
			
		}
	},
	
	cancel : function(e) {
		if(up.dataReader) {
			up.dataReader.abort();
		}
		if(up.dataReader) {
			up.binaryReader.abort();
		}
		if(up.xhr) {
			up.xhr.abort();
		}
		up.uploading = false;
		up.queue = [];
		up.processing = null;
		$j('#drop-area').html('Drag and Drop files to begin...');
		return false;
	},
	
	end			: function( xhr ) {
		console.log( 'good' );
	}
}
